package com.springcloud.tools.token;

import cn.hutool.core.util.IdUtil;
import com.springcloud.tools.exception.IdempotentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author fuc
 * @create 2020-08-19
 */
@Service
public class TokenService {

  @Autowired RedisService redisService;

  public String createToken() {
    String uuid = IdUtil.getSnowflake(1, 1).nextIdStr();
    Boolean result = redisService.setEx(uuid, uuid, 10000L);
    return uuid;
  }

  public Boolean checkToken(HttpServletRequest request) throws IdempotentException {
    String token = request.getHeader("token");
    if (StringUtils.isEmpty(token)) {
      token = request.getParameter("token");
      if (StringUtils.isEmpty(token)) {
        throw new IdempotentException("token 不存在！");
      }
    }
    if (!redisService.exists(token)) {
      throw new IdempotentException("重复的操作！");
    }
    Boolean remove = redisService.remove(token);
    if (Objects.equals(remove, false)) {
      throw new IdempotentException("重复的操作！");
    }
    return true;
  }
}
